package com.example.service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private BindService.MyBinder myBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Toast.makeText(MainActivity.this,"bind！",Toast.LENGTH_LONG).show();
            myBinder = (BindService.MyBinder) iBinder;
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            myBinder = null; // 解绑服务后将 myBinder 置为 null
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            //按钮一启动start_service
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, Start_Service.class);
                startService(intent);
            }
        });
        Button btn2 = findViewById(R.id.button2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            //按钮二绑定Bind_service
            public void onClick(View view) {
                Intent startServiceIntent = new Intent(MainActivity.this, BindService.class);
                startService(startServiceIntent);
                Intent bindServiceintent = new Intent(MainActivity.this, BindService.class);
                bindService(bindServiceintent,connection,0);
            }
        });
        Button btn3 = findViewById(R.id.button3);
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (myBinder != null) {
                    unbindService(connection); // 解绑服务

                }
                if(myBinder==null) {
                    Intent intent = new Intent(MainActivity.this, BindService.class);
                    stopService(intent); // 停止服务
                }
            }
        });
    }

}